<?php

namespace App\Services\Tools;

class MqttService {
    public $mqtt;

    public function __construct() {
        $this->server = env('MQTT_SERVER');     // change if necessary
        $this->port = env('MQTT_PORT');                     // change if necessary
        $this->username = env('MQTT_USERNAME');                   // set your username
        $this->password = env('MQTT_PASSWORD');
    }

    public function subscribe($topic) {
        ignore_user_abort(true); // 后台运行
        set_time_limit(0); // 取消脚本运行时间的超时上限
        date_default_timezone_set('PRC'); //设置中国时区

        $this->mqtt->subscribe($topic, 0);
        while($this->mqtt->proc()){

        }
        $this->mqtt->close();
    }

    public function publish($topic, $content) {
        $client_id = 'php-' . uniqid();
        $this->mqtt = new PhpMqttService($this->server, $this->port, $client_id);
        $this->mqtt->connect(true, null, $this->username, $this->password);

        $this->mqtt->publish($topic, $content, 2);
    }
}


